import { upload } from '@/services/system/image';
import { UploadOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProForm,
  ProFormDateRangePicker,
  ProFormDigit,
  ProFormMoney,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import type { UploadProps } from 'antd';
import { Button, Form, Upload, UploadFile } from 'antd';
import React, { useEffect, useState } from 'react';

export type UpdateFormProps = {
  onSubmit: (values: DISCOUNT.Coupon) => Promise<void>;
  editModalOpen: boolean;
  setEditModalOpen: (open: boolean) => Promise<void>;
  values: Partial<DISCOUNT.Coupon>;
};

const isNumeric = (value: any) => {
  return !isNaN(parseFloat(value)) && !isNaN(value);
};

const EditModal: React.FC<UpdateFormProps> = (props) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [form] = Form.useForm<any>();
  const intl = useIntl();

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) =>
    setFileList(newFileList);

  useEffect(() => {
    if (props.values.image) {
      if (props.values.image.id && props.values.image.fileName && props.values.image.url) {
        let fList: UploadFile[] = [
          {
            uid: props.values.image.id + '',
            name: props.values.image.fileName,
            url: props.values.image.url,
          },
        ];
        setFileList(fList);
      }
    }
    return () => {
      setFileList([]);
    };
  }, [props.values]);

  return (
    <ModalForm<DISCOUNT.Coupon>
      title={
        props.values.id
          ? intl.formatMessage({
              id: 'pages.discount.coupon.createForm.editCoupon',
              defaultMessage: 'Edit Coupon',
            })
          : intl.formatMessage({
              id: 'pages.discount.coupon.createForm.newCoupon',
              defaultMessage: 'New Coupon',
            })
      }
      open={props.editModalOpen}
      onOpenChange={(visible: boolean) => {
        props.setEditModalOpen(visible);
      }}
      form={form}
      onFinish={async (formData: any) => {
        let imageId: string = '';
        const imageFormData = new FormData();
        if (fileList && fileList.length > 0) {
          if (fileList[0].originFileObj) {
            imageFormData.append('files', fileList[0].originFileObj);
          } else if (isNumeric(fileList[0].uid)) {
            imageId = fileList[0].uid;
          }
          const response = await upload(imageFormData);
          if (response.images && response.images.length > 0) {
            imageId = response.images[0].id + '';
          }
        }
        console.log(formData);
        console.log(formData.effectiveTime);
        return props.onSubmit({
          ...props.values,
          ...formData,
          startTime: formData.effectiveTime[0],
          endTime: formData.effectiveTime[1],
          imageId,
        });
      }}
      width={550}
      modalProps={{ destroyOnClose: true }}
    >
      <ProForm.Group>
        <ProFormText
          name="name"
          width="md"
          label={intl.formatMessage({
            id: 'pages.discount.coupon.name',
            defaultMessage: 'name',
          })}
          initialValue={props.values.name}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.discount.coupon.name.ruleName"
                  defaultMessage="name is required"
                />
              ),
            },
          ]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormMoney
          name="money"
          label={intl.formatMessage({
            id: 'pages.discount.coupon.money',
            defaultMessage: 'money',
          })}
          initialValue={props.values.money}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.discount.coupon.money.ruleName"
                  defaultMessage="money is required"
                />
              ),
            },
          ]}
        />
        <ProFormMoney
          name="fullMoney"
          label={intl.formatMessage({
            id: 'pages.discount.coupon.fullMoney',
            defaultMessage: 'full money',
          })}
          initialValue={props.values.fullMoney}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.discount.coupon.fullMoney.ruleName"
                  defaultMessage="full money is required"
                />
              ),
            },
          ]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormDateRangePicker
          name={['effectiveTime']}
          label="优惠券有效时间"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.discount.coupon.effectiveTime.ruleName"
                  defaultMessage="effective time is required"
                />
              ),
            },
          ]}
        />
        <ProFormDigit
          name="expirationDay"
          label="领取优惠券后有效天数"
          initialValue={30}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.discount.coupon.expirationDay.ruleName"
                  defaultMessage="expiration day is required"
                />
              ),
            },
          ]}
        />
      </ProForm.Group>
      <ProFormTextArea
        label={intl.formatMessage({
          id: 'pages.description',
          defaultMessage: 'description',
        })}
        name="description"
        initialValue={props.values.description}
      />
      <>
        <Upload
          listType="picture"
          fileList={fileList}
          onChange={handleChange}
          beforeUpload={() => false}
        >
          <Button type="primary" icon={<UploadOutlined />}>
            优惠券显示图片
          </Button>
        </Upload>
      </>
    </ModalForm>
  );
};

export default EditModal;
